package com.example.sakurasay.main

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandIn
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkOut
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import kotlinx.coroutines.launch
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.graphics.Color
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.sakurasay.debtledger.DebtLedgerScreen
import com.example.sakurasay.passwordbook.PasswordBookScreen
import com.example.sakurasay.quicknotes.QuickNotesScreen
import com.example.sakurasay.settings.SettingsScreen
import com.example.sakurasay.ui.theme.nav_item_selected
import com.example.sakurasay.viewmodels.SettingsViewModel
import com.example.sakurasay.viewmodels.ThemeViewModel

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MainScreen(
    themeViewModel: ThemeViewModel,
    settingsViewModel: SettingsViewModel
) {
    val navController = rememberNavController()
    val navItems = listOf(
        BottomNavItem.QuickNotes,
        BottomNavItem.DebtLedger,
        BottomNavItem.PasswordBook,
    )
    val pagerState = rememberPagerState(pageCount = { navItems.size })
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.collect { page ->
            val route = navItems[page].route
            if (navController.currentDestination?.route != route) {
                navController.navigate(route) {
                    popUpTo(navController.graph.findStartDestination().id) {
                        saveState = true
                    }
                    launchSingleTop = true
                    restoreState = true
                }
            }
        }
    }

    Scaffold(
        topBar = {
            val navBackStackEntry by navController.currentBackStackEntryAsState()
            val currentDestination = navBackStackEntry?.destination
            val currentRoute = currentDestination?.route
            if (currentRoute != "settings" && currentRoute != "oss_licenses") {
                TopAppBar(
                    title = {
                        Text("樱之语")
                    },
                    actions = {
                        IconButton(onClick = { navController.navigate("settings") }) {
                            Icon(Icons.Filled.Settings, contentDescription = "Settings")
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.surface,
                        titleContentColor = MaterialTheme.colorScheme.onSurface,
                        actionIconContentColor = MaterialTheme.colorScheme.onSurface
                    )
                )
            }
        },
        bottomBar = {
            NavigationBar(
                containerColor = MaterialTheme.colorScheme.background,
            ) {
                val navBackStackEntry by navController.currentBackStackEntryAsState()
                val currentDestination = navBackStackEntry?.destination
                navItems.forEachIndexed { index, screen ->
                    val selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true
                    NavigationBarItem(
                        icon = { Icon(screen.icon, contentDescription = screen.label) },
                        label = { Text(screen.label) },
                        selected = selected,
                        onClick = {
                            if (currentDestination?.route == "settings") {
                                navController.popBackStack()
                            }
                            coroutineScope.launch {
                                pagerState.scrollToPage(index)
                            }
                        },
                        colors = NavigationBarItemDefaults.colors(
                            selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
                            selectedTextColor = Color.Black,
                            indicatorColor = nav_item_selected,
                            unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                            unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    )
                }
            }
        }
    ) { innerPadding ->
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentRoute = navBackStackEntry?.destination?.route
        Box(modifier = Modifier.padding(innerPadding)) {
            if (currentRoute !in listOf("settings", "oss_licenses")) {
                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier.fillMaxSize(),
                    beyondBoundsPageCount = 2
                ) { page ->
                    when (navItems[page]) {
                        BottomNavItem.QuickNotes -> QuickNotesScreen()
                        BottomNavItem.DebtLedger -> DebtLedgerScreen()
                        BottomNavItem.PasswordBook -> PasswordBookScreen(navController = navController)
                        else -> {}
                    }
                }
            }

            NavHost(
                navController = navController,
                startDestination = BottomNavItem.QuickNotes.route,
                modifier = Modifier.fillMaxSize(),
                enterTransition = { EnterTransition.None },
                exitTransition = { ExitTransition.None },
                popEnterTransition = { fadeIn(animationSpec = tween(300)) },
                popExitTransition = { fadeOut(animationSpec = tween(300)) }
            ) {
                composable(BottomNavItem.QuickNotes.route) {  }
                composable(BottomNavItem.DebtLedger.route) {  }
                composable(BottomNavItem.PasswordBook.route) { }
                composable(
                    "settings",
                    enterTransition = {
                        expandIn(
                            animationSpec = tween(300),
                            expandFrom = Alignment.TopEnd
                        ) + fadeIn(animationSpec = tween(300))
                    },
                    exitTransition = {
                        shrinkOut(
                            animationSpec = tween(300),
                            shrinkTowards = Alignment.TopEnd
                        ) + fadeOut(animationSpec = tween(300))
                    }
                ) {
                    SettingsScreen(
                        themeViewModel = themeViewModel,
                        settingsViewModel = settingsViewModel,
                        onNavigateBack = { navController.popBackStack() },
                        onNavigateToOssLicenses = { navController.navigate("oss_licenses") }
                    )
                }
                composable(
                    "oss_licenses",
                    enterTransition = {
                        expandIn(
                            animationSpec = tween(300),
                            expandFrom = Alignment.TopEnd
                        ) + fadeIn(animationSpec = tween(300))
                    },
                    exitTransition = {
                        shrinkOut(
                            animationSpec = tween(300),
                            shrinkTowards = Alignment.TopEnd
                        ) + fadeOut(animationSpec = tween(300))
                    }
                ) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = { Text("开源许可") },
                                navigationIcon = {
                                    IconButton(onClick = { navController.popBackStack() }) {
                                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                                    }
                                }
                            )
                        }
                    ) { padding ->
                        Box(
                            modifier = Modifier
                                .padding(padding)
                                .fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text("开源许可页面")
                        }
                    }
                }
            }
        }
    }
}